package com.itheima.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.bean.Employee;
import com.itheima.common.PageParm;
import com.itheima.common.R;
import com.itheima.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService em;

    @PostMapping("/employee/login")
    public R login(@RequestBody Employee employee , HttpSession httpSession){
        System.out.println(employee);
        employee.setPassword(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()));
        Employee login = em.login(employee);

        if(login!=null) {

            System.out.println(login);
            httpSession.setAttribute("employee",login);
            return R.success(login);
        }

        else return R.error("登陆失败！！！");

    }

    @PostMapping("/employee/logout")
    public R logout(HttpServletRequest request){
        //清理sesssion
        request.getSession().removeAttribute("employee");
        //推出成功
        return R.success("退出成功");
    }

    @PostMapping("/employee")
    public R add(@RequestBody Employee employee,HttpServletRequest request){


        Employee employee1 =(Employee) request.getSession().getAttribute("employee");

        System.out.println(employee1);
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
  /*      employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(employee1.getId());
        employee.setCreateUser(employee1.getId());*/
        int row = em.add(employee);
        if(row>0){
            return R.success("添加成功");
        }

        else return R.error("添加失败！！！");
    }


    @GetMapping("/employee/page")
    public R selectPage( PageParm parm){
        IPage<Employee> employeeIPage = em.selectPage(parm);
        return R.success(employeeIPage);
    }

    @PutMapping("/employee")
    public R Update(@RequestBody Employee employee ,HttpSession session){
//        employee.setUpdateTime(LocalDateTime.now());
        Employee employee1 =(Employee) session.getAttribute("employee");
//        employee.setUpdateUser(employee1.getId());
        int update = em.update(employee);
        if(update>0){
            return R.success("更新成功");
        }
        else return R.error("更新失败");

    }



}
